package l.l.w.leetcode.CombinationSum;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by llw on 2017/11/7.
 */
public class CombinationSum {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> result = new LinkedList<>();
        LinkedList<Integer> one = new LinkedList<>();
        getResult(candidates,result,one,target,0);

        return result;
    }

    private void getResult(int[] candidates, List<List<Integer>> result, LinkedList<Integer> one, int target, int i) {
        if(target > 0){
            for(int j = i; j < candidates.length && candidates[j] <= target; ++j){
                one.add(candidates[j]);
                getResult(candidates,result,one,target - candidates[j],j);
                one.removeLast();
            }
        }else if(target ==0){
            result.add(new LinkedList<Integer>(one));
        }
    }

    public static void main(String[] args) {
        int[] a = {2, 3, 6, 7};
        List<List<Integer>> result = new CombinationSum().combinationSum(a, 7);
        System.out.println(result);
    }
}
